// Ensure SQLite is dynamically linked
#ifdef SQLITE_STATIC
#undef SQLITE_STATIC
#endif

#include "login_interface.h"
#include "global_vars.h"
#include <fstream>
#include <sstream>

// Helper function to read file contents
static std::string readFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        return "";
    }

    std::stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

// Get index page HTML
crow::response LoginInterface::getIndexPage() {
    crow::response res;
    res.set_header("Content-Type", "text/html; charset=UTF-8");
    
    // Read HTML content from file
    std::string html = readFile("html/index.html");
    
    // If file reading fails, return error message
    if (html.empty()) {
        html = "<html><body><h1>Error: Unable to load index page</h1><p>Please ensure html/index.html file exists and is readable.</p></body></html>";
    }
    
    res.body = html;
    return res;
}

// Get dashboard HTML
crow::response LoginInterface::getDashboardPage() {
    crow::response res;
    res.set_header("Content-Type", "text/html; charset=UTF-8");
    
    // Read HTML content from file
    std::string html = readFile("html/dashboard.html");
    
    // If file reading fails, return error message
    if (html.empty()) {
        html = "<html><body><h1>Error: Unable to load dashboard</h1><p>Please ensure html/dashboard.html file exists and is readable.</p></body></html>";
    }
    
    res.body = html;
    return res;
}

// Get post page HTML
crow::response LoginInterface::getPostPage() {
    crow::response res;
    res.set_header("Content-Type", "text/html; charset=UTF-8");
    
    // Read HTML content from file
    std::string html = readFile("html/post.html");
    
    // If file reading fails, return error message
    if (html.empty()) {
        html = "<html><body><h1>Error: Unable to load post page</h1><p>Please ensure html/post.html file exists and is readable.</p></body></html>";
    }
    
    res.body = html;
    return res;
}

// Set up login-related routes
void LoginInterface::setupLoginRoutes(crow::SimpleApp& app, Database& db) {
    // Simplified route setup using traditional C++ function object syntax
    
    // Index page route - removed to avoid conflict with main.cpp
    // The index route is now handled in main.cpp
    
    // Dashboard route
    CROW_ROUTE(app, "/dashboard")
    (
        []() {
            return LoginInterface::getDashboardPage();
        }
    );
    
    // Post page route
    CROW_ROUTE(app, "/post.html")
    (
        []() {
            return LoginInterface::getPostPage();
        }
    );

    // Login API route
    CROW_ROUTE(app, "/login")
    .methods(crow::HTTPMethod::Post)
    (
        [&db](const crow::request& req) {
            auto x = crow::json::load(req.body);
            if (!x) {
                crow::json::wvalue result;
                result["success"] = false;
                result["message"] = "Invalid JSON format";
                return crow::response(400, result);
            }

            std::string username = x["username"].s();
            std::string password = x["password"].s();

            int user_id = db.loginUser(username, password);
            if (user_id > 0) {
                // 登录成功，设置全局用户ID
                set_current_user_id(user_id);
                
                crow::json::wvalue result;
                result["success"] = true;
                result["message"] = "Login successful";
                result["user_id"] = user_id;
                return crow::response(200, result);
            }
            else {
                // 登录失败，清除用户ID
                set_current_user_id(-1);
                
                crow::json::wvalue result;
                result["success"] = false;
                result["message"] = "Invalid username or password";
                return crow::response(401, result);
            }
        }
    );

    // Register API route
    CROW_ROUTE(app, "/register")
    .methods(crow::HTTPMethod::Post)
    (
        [&db](const crow::request& req) {
            auto x = crow::json::load(req.body);
            if (!x) {
                crow::json::wvalue result;
                result["success"] = false;
                result["message"] = "Invalid JSON format";
                return crow::response(400, result);
            }

            std::string username = x["username"].s();
            std::string password = x["password"].s();

            if (db.registerUser(username, password)) {
                crow::json::wvalue result;
                result["success"] = true;
                result["message"] = "Registration successful";
                return crow::response(200, result);
            }
            else {
                crow::json::wvalue result;
                result["success"] = false;
                result["message"] = "Registration failed, username may already exist";
                return crow::response(400, result);
            }
        }
    );
} 